﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Media.SpeechRecognition;
using Windows.Storage;
using Windows.UI.Popups;

namespace VoiceSnap
{
    internal static class AppUtil
    {
        /// <summary>
        /// Install voice command set from voice command definition (VCD) file.
        /// </summary>
        /// <returns></returns>
        public static async Task LoadVoiceCommandDefinition()
        {
            Uri uri = new Uri("ms-appx:///VCD_81.xml", UriKind.Absolute);
            StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uri);

            // Install voice commands
            // If voice commands were already installed for the application, this method call will not take any action.
            try
            {
                await VoiceCommandManager.InstallCommandSetsFromStorageFileAsync(file);
            }
            catch (Exception ex)
            {
                string errorMessage = String.Format(
                    "An error was encountered installing the Voice Command Definition file: \r\n {0:x} \r\n {1}",
                    ex.HResult,
                    ex.Message);
                new MessageDialog(errorMessage).ShowAsync();
            }
        }

        /// <summary>
        /// This will load pre-packaged images from App's local data into the Saved pictures folder of phone's photo library.
        /// </summary>
        /// <returns></returns>
        public static async Task PopulatePhotoAlbum()
        {
            // Load photos and save with tags
            for (int itr = 0; itr < Constants.PhotoSet.Count; itr++)
            {
                // Create a photo placeholder memory
                StorageFile newPhoto = await Constants.ImageSearchLocation.CreateFileAsync(
                "photo" + itr.ToString() + ".jpg",
                CreationCollisionOption.ReplaceExisting);

                string uriStr = string.Format(Constants.PhotoSet[itr].Value);
                Uri uri = new Uri(uriStr, UriKind.Absolute);

                StorageFile currFile = await StorageFile.GetFileFromApplicationUriAsync(uri);
                await currFile.CopyAndReplaceAsync(newPhoto);

                // Add tags to the photo
                List<string> currPhotoTags = Constants.PhotoSet[itr].Key.Split(';').ToList();
                var imageProperties = await newPhoto.Properties.GetImagePropertiesAsync();
                foreach (string currTag in currPhotoTags)
                {
                    imageProperties.Keywords.Add(currTag);
                }
                await imageProperties.SavePropertiesAsync();
            }

            // Workaround: populating the images on slow storage devices sometimes doesn't complete fast enough.
            await Task.Delay(2000);
        }
    }
}
